from django.conf import settings
from rest_framework.authentication import BaseAuthentication
import jwt
from jwt import exceptions
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.exceptions import AuthenticationFailed, NotAuthenticated, PermissionDenied,MethodNotAllowed
from rest_framework import status
from rest_framework.exceptions import APIException

class CustomAuthenticationFailedException(APIException):
    status_code = status.HTTP_401_UNAUTHORIZED
    default_detail = 'Incorrect authentication credentials.'
    default_code = 'authentication_failed'

# class JWTAuthentication(BaseAuthentication):
#
#     def authenticate(self, request):
#         token = request.META.get('HTTP_AUTHORIZATION')
#         # print("接收到的token:", token)
#         salt = settings.SECRET_KEY
#         try:
#             token = token.replace('Bearer ', '') # 去掉Bearer
#             payload = jwt.decode(token, salt, algorithms=['HS256'])
#         except exceptions.ExpiredSignatureError:
#             raise CustomAuthenticationFailedException({'code': 1003, 'error': 'token已失效'})
#         except exceptions.DecodeError:
#             raise CustomAuthenticationFailedException({'code': 1003, 'error': 'token认证失败'})
#         except exceptions.InvalidTokenError:
#             raise CustomAuthenticationFailedException({'code': 1003, 'error': '非法的token'})
#         return (payload, token)  #request.user取到的是payload，request.auth取到的是token
class JWTAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')

        # 检查 token 是否为 None
        if token is None:
            raise NotAuthenticated('未提供token')

        try:
            token = token.replace('Bearer ', '')  # 去掉 Bearer
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
        except exceptions.ExpiredSignatureError:
            raise CustomAuthenticationFailedException({'code': 1003, 'error': 'token已失效'})
        except exceptions.DecodeError:
            raise CustomAuthenticationFailedException({'code': 1003, 'error': 'token认证失败'})
        except exceptions.InvalidTokenError:
            raise CustomAuthenticationFailedException({'code': 1003, 'error': '非法的token'})

        return (payload, token)  # request.user 取到的是 payload，request.auth 取到的是 token
